#include "VReceive.h"
#include "ui_VReceive.h"
#include "CSettings.h"
#include "CConversion.h"
#include <QTextCharFormat>
#include "qcustomplot.h"
#include "VDialogProtocal.h"
#include <QTime>






VReceive::VReceive(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::VReceive)
{
    ui->setupUi(this);
    //ui->textEdit_receive->setReadOnly(true);
   // ui->textEdit_receive->
//    ui->textEdit_receive->setCursor()
//    ui->textEdit_receive->cursorVisible(true);

//    ui->textEdit_receive->setCursor()
     this->grabKeyboard();
    ui->textEdit_receive->moveCursor(QTextCursor::End);
    //ui->textEdit_receive->setTextBackgroundColor(QColor("#000000"));
    //setStyleSheet
//    ui->textEdit_receive->setStyleSheet("background-color: black");
//    ui->textEdit_receive->setTextColor(QColor("#ffffff"));

    ui->textEdit_receive->setFontFamily("微软雅黑");

    ui->textEdit_receive->setFontPointSize(10);

//      ui->textEdit_receive->setStyleSheet()

//    QFont font;
//    font.setFamily("等线,consolas");
//    font.setStyleStrategy(QFont::PreferAntialias);
//    font.setPixelSize(9);
//    ui->textEdit_receive->setFont(font);

}

VReceive::~VReceive()
{
    delete ui;
}

void VReceive::setConnectionProxy(CConnectManager *pConnectManager)
{
    m_pConnectManager = pConnectManager;
    connect(m_pConnectManager,&AbsConnection::sigStateChanged,[=](AbsConnection::EnmState enmState){
        this->stateChanged(enmState);
    });
    connect(m_pConnectManager,&AbsConnection::sigConnectChanged,[=](QString strIp,quint16 nPort,bool bState){
        this->connectStateChanged(strIp,nPort,bState);
    });
    connect(m_pConnectManager,&AbsConnection::sigDataArrive,[=](QString strIp,quint16 nPort,QByteArray byteArr){
        this->dataArrive(strIp,nPort,byteArr);
        if(ui->chart->isEnabled())
            ui->chart->dataArrive(strIp,nPort,byteArr); // 绘图
    });
    connect(m_pConnectManager,&CConnectManager::sigProtocolChanged,[=](AbsConnection::EnmProtocolType enmType){
        this->protocolChanged(enmType);
    });
    connect(m_pConnectManager,&CConnectManager::sigSend,[=](QByteArray byteArr){
        this->send(byteArr);
    });
}

void VReceive::dataArrive(QString strIp, quint16 nPort, QByteArray byteArr)
{
    Q_UNUSED(strIp)
    Q_UNUSED(nPort)

    if(ui->checkBox_stop->isChecked()) //停止显示
        return ;




    QByteArray MainSerialRecvData;
     char temp[10]={0};

     char c;



    ///////////////////////////////////////////////////////////////////////////////////////////////////


//    if(byteArr.replace('\r',' '))
//    {

//    }

    byteArr.replace('\r',' ');

   // qDebug()<<"buf size"<<byteArr.size();

    if(byteArr.at(0) == 0x08 && byteArr.size()==3)
    {
        text_buf.chop(1);
    }
    else

  {
        //转换文本
        QString strText;
        if(ui->checkBox_hex->isChecked()){
            strText = CConversion::byteArray2HexStr(byteArr); //@TODO 进制非法应有提示 比如包含:R
        }else{
            strText = CSettings::getInstance()->byteArray2Str(byteArr);
        }
        //时间戳
        if(ui->checkBox_time->isChecked())
            strText = timestamp() + strText;


         text_buf += strText;

  //  text_buf += byteArr;
   }


    QTextCursor cursor = ui->textEdit_receive->textCursor();

         ui->textEdit_receive->setText(text_buf);
         cursor.movePosition(QTextCursor::End);
         ui->textEdit_receive->setTextCursor(cursor);

         if(text_buf.size() > 1024000)// 暂定存 1MB 的数据
             text_buf.remove(0,text_buf.size() - 1024000);
     // qDebug()<<"--str buf size "<<text_buf.size(); //




//    MainSerialRecvData = byteArr;

//    int size = MainSerialRecvData.size();
//    if(size>2)
//    {
//        if(MainSerialRecvData.at(size-2) == '\r' && MainSerialRecvData.at(size-1) == '\n')
//        {

//            MainSerialRecvData[size - 1] = 0;
//        }

//    }

//   //qDebug("rec data");
//    int count = MainSerialRecvData.count();





//    for(int i = 0;i<count;i++){
//        //qDebug("0x%x",MainSerialRecvData.at(i));
//        temp[0] = MainSerialRecvData[i];
//        temp[1] = 0;
//        if(i<count-1)
//        c = MainSerialRecvData[i+1];

//        if((temp[0] >= 0) && (temp[0] <= 0x7e))
//        {//ASCII

////            if((temp[0] = 0x0d )&& (c == 0x0a))
////            {
////                MainSerialRecvData[i+1] = 0x31;

////            }


//            if(temp[0] == 0x08)
//            {// '/b'：backspace键
//                ui->textEdit_receive->textCursor().deletePreviousChar();//删除光标后面一个字符
//            }
//            else
//            {
//               ui->textEdit_receive->textCursor().insertText(temp);//把字符显示到textedit里
//            }
//            //移动滚动条到底部
//            QScrollBar *scrollbar = ui->textEdit_receive->verticalScrollBar();
//            if (scrollbar)
//            {
//                  scrollbar->setSliderPosition(scrollbar->maximum());
//            }
//        }
//    }



    ////////////////////////////////////////////////////////////////////////////////////////////////////

    /*
    int len = byteArr.size();

    if(byteArr.right(2) == "\r\n")
    {
        byteArr.chop(1);
    }
//    if(len >1)
//    {


//    if(byteArr.at(len - 2) == 0x0d && byteArr.at(len- 3) == 0x0d)
//        {

//       // byteArr.resize(len - 1);
//        }
//    }
//    if(byteArr.at(0) == 0x08)
//      ui->textEdit_receive->textCursor().deletePreviousChar();//删除光标后面一个字符

    //转换文本
    QString strText;
    if(ui->checkBox_hex->isChecked()){
        strText = CConversion::byteArray2HexStr(byteArr); //@TODO 进制非法应有提示 比如包含:R
    }else{
        strText = CSettings::getInstance()->byteArray2Str(byteArr);
    }
    //时间戳
    if(ui->checkBox_time->isChecked())
        strText = timestamp() + strText;


//    if(strText.right(2) == "\r\n")
//        strText.chop(1);
//    else if(strText.right(3) == "\r\r\n")
//    {
//    strText.chop(2);
//    }


    //设置文本样式 追加 显示
//    QTextCharFormat textFmt;
//    textFmt.setFontItalic(false);
//    textFmt.setForeground(QColor("black"));

//    ui->textEdit_receive->mergeCurrentCharFormat(textFmt);
   // ui->textEdit_receive->append(strText);
    ui->textEdit_receive->insertPlainText(strText);
   // ui->textEdit_receive->setAlignment(Qt::AlignLeft);
    ui->textEdit_receive->moveCursor(QTextCursor::End);

   */
}

void VReceive::send(QByteArray byteArr)
{
    if(false == ui->checkBox_display_send->isChecked())
        return ;

    //转换文本
    QString strText;
    if(ui->checkBox_hex->isChecked()){ //@BUG 应判断发送是否为十六进制 不是判断这个
        strText = CConversion::byteArray2HexStr(byteArr); //@TODO 进制非法应有提示 比如包含字母:R
    }else{
        strText = CSettings::getInstance()->byteArray2Str(byteArr);
    }

    //时间戳
    if(ui->checkBox_time->isChecked())
        strText = timestamp() + strText;

    //设置文本样式  绿色 显示
    QTextCharFormat textFmt;
    textFmt.setFontItalic(true);
    textFmt.setForeground(QColor("#47d147"));
    ui->textEdit_receive->mergeCurrentCharFormat(textFmt);
    ui->textEdit_receive->append(strText);
    ui->textEdit_receive->setAlignment(Qt::AlignRight);

    ui->textEdit_receive->moveCursor(QTextCursor::End);
}

void VReceive::on_toolButton_clear_clicked()
{
    text_buf.clear();
    ui->textEdit_receive->clear();
}

QString VReceive::timestamp()
{
   return QTime::currentTime().toString() + "  ";
}

void VReceive::on_textEdit_receive_textChanged()
{

  //  ui->textEdit_receive->text
}
void VReceive::keyPressEvent(QKeyEvent *ev)
{
    int code = 0xFF;
    static uint8_t falg = 0;
   // unsigned char controlkey[5]={0x1b,0x5b,0x00};
   QByteArray controlkey;
   controlkey.resize(3);
   controlkey[0] = 0x1b;
   controlkey[1] = 0x5b;


    qDebug("键值：0x%x",ev->key());

 //   ui->textEdit_receive->toPlainText().chop(1);

    if(!ui->textEdit_receive->hasFocus()){//判断光标是否在textEdit控件上
        //this->grabKeyboard();
        this->releaseKeyboard();
        falg = 0;
        qDebug()<<"release key board";

        return;
    }
    else
    {
        qDebug()<<"reconnect key board";
        if(falg == 1)
        {}
        else
        {this->grabKeyboard();falg = 1; }

    }

    /*
     * handle control key
     * up key  : 0x1b 0x5b 0x41
     * down key: 0x1b 0x5b 0x42
     * right key:0x1b 0x5b 0x43
     * left key: 0x1b 0x5b 0x44
     */
controlkey[2] = 0x00;
    switch (ev->key()) {
    case Qt::Key_Left:
        controlkey[2] = 0x44;
       // ui->textEdit_receive->moveCursor(QTextCursor::Left);
        break;
    case Qt::Key_Right:
        controlkey[2] = 0x43;
       // ui->textEdit_receive->moveCursor(QTextCursor::Right);
        break;
    case Qt::Key_Up:
        controlkey[2] = 0x41;
        break;
    case Qt::Key_Down:
        controlkey[2] = 0x42;
        break;


    default:
        QString text = ev->text();
        if(text.size() > 0){
            code = text.at(0).toLatin1();
            if((code >= 0) && (code <= 0x7e)){//ASCII
                if(code == '\n'||code == '\r'){//回车按键按下时，将光标移动到末尾
                    ui->textEdit_receive->moveCursor(QTextCursor::End);
                }
                controlkey.resize(1);
                controlkey[0] = code;
                emit ssend_data(controlkey);

                }
            }

        break;
    }


        /*
    case Qt::Key_Return: controlkey[0] = 0x0d;  controlkey.resize(1);// ui->textEdit_receive->moveCursor(QTextCursor::End); ui->textEdit_receive->textCursor().deletePreviousChar();//删除光标后面一个字符 break;
    case Qt::Key_Enter:  controlkey[0] = 0x0d;  controlkey.resize(1); // ui->textEdit_receive->moveCursor(QTextCursor::End); ui->textEdit_receive->textCursor().deletePreviousChar();//删除光标后面一个字符   break;
    //case Qt::Key_Tab:     ui->textEdit_receive->moveCursor(QTextCursor::End);  ui->textEdit_receive->textCursor().deletePreviousChar();//删除光标后面一个字符   break;
         break;
    default: // 字符按键
        {


        if(LOBYTE(GetKeyState(VK_CAPITAL))) {
            controlkey[0] = ( ev->key());
            // mp_capsWid->show();
        }
        else {
            controlkey[0] = ( ev->key()+32);
            // mp_capsWid->hide();
        }
             controlkey.resize(1);
          //controlkey.clear();controlkey[0] = ev->key();
        //  controlkey.append( ev->key());
       //   ui->textEdit_receive->textCursor().deletePreviousChar();//删除光标后面一个字符

        }
      break;
        */


      //


    if(controlkey.size()>1){

       // m_pConnectManager->send()

     emit ssend_data(controlkey);
    //    port->write((const char*)&controlkey[0],3);
    }

    //qDebug("0x%x  %c",(char)code,(char)code);
    //QWidget::keyPressEvent(ev);
}
bool VReceive::event(QEvent *event)

 {

    QByteArray ba;

    ba.append(0x09);
     if (event->type() == QEvent::KeyPress) {

         QKeyEvent *ke = static_cast<QKeyEvent *>(event);

         if (ke->key() == Qt::Key_Tab) {

             qDebug()<<"tab :";
             // special tab handling here
           emit ssend_data(ba);
             return true;

         }

     }


     return QWidget::event(event);

 }
